<template>
  <div class="login">
    <el-card>
      <template #header>
        <div class="">
          <span>通用后台管理系统</span>
        </div>
      </template>
      <el-form label-width="80px" :model="form" ref="form" :rules="rules">
        <el-form-item label="用户名" prop="username" ref="formItem">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login('form')">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from '@/api/api.js'
import { setToken } from '@/utils/setToken.js'

export default {
  data() {
    return {
      form: {
        username: "",
        password: ""
      },
      rules: {
        username: [{ required: true, message: '请输入账户', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }

    }
  },
  methods: {
    login(form) {
      this.$refs[form].validate((isValid) => {
        console.log(isValid);
        if (isValid) {
          console.log("this.form的值===>", this.form);
          console.log("this.$refs['form']的值===>", this.$refs['form']);
          login(this.form).then(res => {
            console.log('res=========>',res);
            console.log('res.data=========>',res.data);
                if (res.data.status === 200) {
                    setToken('username', res.data.username)
                    setToken('token', res.data.token)
                    this.$message({message: res.data.message, type: 'success'})
                    this.$router.push('/home')
                }
           })
        } else {
          console.error(this.form);
        }
      })
    }
  }
}
</script>

<style></style>